import React, { Component } from 'react';
import ReactEcharts from 'echarts-for-react';
import axios from '../api'
import xyz from './xyz'

import echarts from 'echarts';

export default class TopSite extends Component {
  constructor(props) {
    super(props);
    this.state = {
      option: {
        xAxis: { type: 'category', name: '站厅', nameTextStyle: { color: '#ffffff' }, splitLine: { show: true, lineStyle: { width: 0 } } },
        yAxis: { type: 'value', name: '客流量(人)', nameTextStyle: { color: '#ffffff' } },
        grid: { top: 40, bottom: 40, left: 60, right: 10 },
        legend: { right: 10, data: [{ name: '上行客流', icon: 'react' }, { name: '下行客流', icon: 'react' }], orient: 'vertical' },
        series: []
      }
    };
  }

  componentWillMount () {
    echarts.registerTheme('xyz', xyz);
  }

  componentDidMount () {
    this.tick()
    this.timerID = setInterval(
      () => this.tick(),
      15 * 60 * 1000
    );
  }

  componentWillUnmount () {
    clearInterval(this.timerID);
  }

  tick () {
    axios.get('/top_site').then(({ data: { site, up, down } }) => {
      this.genData(site, up, down)
    })
  }

  genData (site, up, down) {
    const { option } = this.state
    const seriesItem = (data, desc, color1, color2) => Object.assign({}, {
      name: `${desc}行客流`, type: 'bar', barWidth: 15, barGap: 0, data, itemStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0.5, color: color1 // 0% 处的颜色
          }, {
            offset: 1, color: color2 // 100% 处的颜色
          }],
        }
      }
    })
    const series = [seriesItem(up, '上', '#1688FD', '#59E8E5'), seriesItem(down, '下', '#F71F40', '#C402EE')]
    this.setState({ option: Object.assign({}, option, { series }, { xAxis: { type: 'category', data: site, axisLabel: { interval: 0 } } }) })
  }

  render () {
    return (
      <ReactEcharts
        option={this.state.option}
        notMerge={true}
        lazyUpdate={true}
        style={{ height: '100%' }}
        theme={'xyz'} />
    )
  }
}